package com.qef.com.mmovie.fragment;

import android.app.Activity;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.Uri;
import android.os.Environment;
import android.os.Parcelable;
import android.provider.MediaStore;
import android.support.v7.widget.Toolbar;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVFile;
import com.avos.avoscloud.SaveCallback;
import com.bumptech.glide.Glide;
import com.qef.com.mmovie.App;
import com.qef.com.mmovie.IView;
import com.qef.com.mmovie.R;
import com.qef.com.mmovie.activity.LoginActivity;
import com.qef.com.mmovie.base.SimpleActivity;
import com.qef.com.mmovie.entity.User;
import com.qef.com.mmovie.entity.event.UpUserInfoEvent;
import com.qef.com.mmovie.utils.HindToolbar;
import com.qef.com.mmovie.utils.PermissionUtil;
import com.qef.com.mmovie.utils.PopWindowUtils;
import com.qef.com.mmovie.utils.ToastUtil;
import com.qef.com.mmovie.utils.UIHelper;
import com.tbruyelle.rxpermissions2.RxPermissions;

import org.greenrobot.eventbus.EventBus;

import java.io.FileNotFoundException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;

/**
 * Created by feq on 2017/4/22.
 */

public class UpDataPerson extends SimpleActivity {
    @BindView(R.id.toolbar)
    Toolbar toolbar;
    private Parcelable dataBean;
    @BindView(R.id.phonenumber)
    TextView mPhoneNm;
    @BindView(R.id.userid)
    TextView mUserid;
    @BindView(R.id.guide_head)
    CircleImageView mHeadImg;
    @BindView(R.id.rela_btn)
    RelativeLayout imgBtn;
    @BindView(R.id.rela_btn2)
    RelativeLayout upUerName;
    @BindView(R.id.root_view)
    View rootView;
    @BindView(R.id.name_tv)
    TextView tvName;
    @BindView(R.id.bt_exit)
    Button btExit;
    @BindView(R.id.reset_pwd)
    RelativeLayout resetPwd;
    public static final int CUT_PICTURE = 1;
    private Uri cropImageUri, imageUriFromCamera;
    public static final int SHOW_PICTURE = 2;
    public static final int Make_CAMERE = 3;
    private Uri imageFilePath;
    private static final int HEAD = 100;
    private static final int ALIAS = 101;

    @Override
    protected int getLayout() {
        HindToolbar.setHintWindowTitle(getWindow());
        return R.layout.layout_update_person;
    }

    @Override
    protected void initEventAndData() {
        initView();
        initData();
    }

    private void initData() {
        mPhoneNm.setText(User.getCurrenUser().getUsername());
        mUserid.setText(User.getCurrenUser().getObjectId());
        tvName.setText(getTextx(ALIAS));
        Glide.with(App.getInstance()).load(getTextx(HEAD)).into(mHeadImg);
        eventPost(1500);
        //注册eventbus
//        EventBus.getDefault().register(this);
    }

    public String getTextx(int type) {
        switch (type) {
            case ALIAS:
                return null == User.getAlias() ? "" : User.getAlias().toString();
            case HEAD:
                return null == User.getHead() ? "" : User.getHead().toString();
        }
        return null;
    }


    private void initView() {
        ButterKnife.bind(this);
        toolbar.setNavigationIcon(R.mipmap.ic_arrow_back_white_24dp);
        toolbar.setNavigationOnClickListener(v -> onBackPressed());
        toolbar.setTitle("修改个人信息");
        toolbar.setTitleTextColor(Color.WHITE);
    }

    @OnClick({R.id.rela_btn, R.id.rela_btn2, R.id.bt_exit, R.id.reset_pwd})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rela_btn:
                //设置用户头像
                changeHead();
                break;
            case R.id.rela_btn2:
                //设置用户昵称
                setAlias();
                break;
            case R.id.bt_exit:
                eventPost(0);
                User.exit();
//                startActivity(new Intent(this, LoginActivity.class));
                UIHelper.goLoginActivity(this);
                finish();
                break;
            case R.id.reset_pwd:
                resetPws();
                break;
        }
    }

    private void setAlias() {
        PopWindowUtils.with(App.getInstance()).loadLayout(R.layout.pop_rename)
                .setOnCustomListener((view, popupWindow) -> {
                    EditText etName = (EditText) view.findViewById(R.id.et_rename);
                    view.findViewById(R.id.bt_sure).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if (etName.getText().length() != 0) {
                                String name = etName.getText().toString();
                                User.setAlias(name);
                                tvName.setText(name);
                            }
                            popupWindow.dismiss();
                            //延迟1.5秒发送消息通知更改用户信息
                            eventPost(1500);
                        }
                    });
                }).ShowLocation(rootView, Gravity.BOTTOM, 0, 0);
    }

    private void resetPws() {
        PopWindowUtils.with(App.getInstance()).loadLayout(R.layout.pop_reset_pwd)
                .setOnCustomListener((view, popupWindow) -> {
                    EditText etPwdOld = (EditText) view.findViewById(R.id.et_rename_old);
                    EditText etPwdNew = (EditText) view.findViewById(R.id.et_rename_new);
                    view.findViewById(R.id.bt_sure).setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            String newPwd = etPwdNew.getText().toString();
                            String oldPwd = etPwdOld.getText().toString();

//                            if (newPwd.length() != 0 && oldPwd.length() != 0) {
//                                String password = (String) User.getCurrenUser().get("password");
//                                if (User.getCurrenUser().get("password").equals(oldPwd)) {
//                                    User.resetPwd(newPwd);
//                                    ToastUtil.showToast(App.getInstance(), "修改成功");
//                                } else {
//                                    ToastUtil.showToast(App.getInstance(), "旧密码错误");
//                                }
//                            } else {
//                                ToastUtil.showToast(App.getInstance(), "修改失败");
//                            }
                            ToastUtil.showToast(App.getInstance(), "修改失败");
                            popupWindow.dismiss();
                            //延迟1.5秒发送消息通知更改用户信息
                            eventPost(1500);
                        }
                    });
                }).ShowLocation(rootView, Gravity.BOTTOM, 0, 0);
    }

    private void changeHead() {
        PopWindowUtils.with(App.getInstance()).
                loadLayout(R.layout.common_pop_img)
                .setOnCustomListener((view, popupWindow) -> {
                            view.findViewById(R.id.item_popupwindows_camera)
                                    .setOnClickListener(view1 -> {
                                        PermissionUtil.launchCamera(() -> {

                                        }, new RxPermissions(this), new IView() {

                                            @Override
                                            public void success(String message) {
                                                showPictureByCamera();
                                            }

                                            @Override
                                            public void error(String message) {
                                                ToastUtil.showToast(mContext, message);
                                            }
                                        });
                                        popupWindow.dismiss();
                                    });
                            view.findViewById(R.id.item_popupwindows_photo).
                                    setOnClickListener(view12 -> {
                                        PermissionUtil.externalStorage(() -> {

                                        }, new RxPermissions(this), new IView() {

                                            @Override
                                            public void success(String message) {
                                                showChoosePicture();
                                            }

                                            @Override
                                            public void error(String message) {
                                                ToastUtil.showToast(mContext, message);
                                            }
                                        });
                                        popupWindow.dismiss();
                                    });
                            view.findViewById(R.id.item_popupwindows_cancel)
                                    .setOnClickListener(view13 -> {

                                            }
                                    );
                        }
                )
                .ShowLocation(rootView, Gravity.BOTTOM, 0, 0);
    }

    private void showChoosePicture() {
        Intent intent = new Intent(Intent.ACTION_PICK, null);
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
        startActivityForResult(intent, CUT_PICTURE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode) {
            case CUT_PICTURE:
                if (data != null) {
                    cropImage(this, data.getData(), false);
                }
                break;
            case SHOW_PICTURE:
                //返回裁剪后的头像
                if (resultCode == RESULT_OK) {
                    upDataHead();
                    try {
                        //将output_image.jpg对象解析成Bitmap对象，然后设置到ImageView中显示出来
                        Bitmap bitmap = BitmapFactory.decodeStream(getContentResolver()
                                .openInputStream(cropImageUri));
                        ImageView head = (ImageView) findViewById(R.id.guide_head);
                        head.setImageBitmap(bitmap);
                        //延迟1.5秒发送消息通知更改用户信息
                        eventPost(1500);
                    } catch (FileNotFoundException e) {
                        e.printStackTrace();
                    }
                }
                break;
            // 如果是调用相机拍照时
            case Make_CAMERE:
                if (imageUriFromCamera != null && resultCode == -1) {
                    cropImage(this, imageUriFromCamera, false);
                }
                break;
        }
    }

    private void eventPost(int time) {
        //通知系统更新个人信息数据
        App.getThreadPool().execute(() -> {
            try {
                Thread.sleep(time);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            EventBus.getDefault().post(new UpUserInfoEvent());
        });
    }

    public static String getRealPathFromUri(Context context, Uri contentUri) {
        Cursor cursor = null;
        try {
            String[] proj = {MediaStore.Images.Media.DATA};
            cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } finally {
            if (cursor != null) {
                cursor.close();
            }
        }
    }

    private void upDataHead() {
        try {
            AVFile file = AVFile.withAbsoluteLocalPath("LeanCloud.png",
                    getRealPathFromUri(App.getInstance(), cropImageUri));
            file.saveInBackground(new SaveCallback() {
                @Override
                public void done(AVException e) {
                    //图片上传成功保存到用户数据中
                    User.getCurrenUser().put("head", file.getUrl());
                    User.getCurrenUser().saveInBackground();
                }
            });
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

    public void cropImage(Activity context, Uri srcUri, boolean bgimg) {
        cropImageUri = createImagePathUri(context);

        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(srcUri, "image/*");
        intent.putExtra("crop", "true");

        if (bgimg) {
            intent.putExtra("aspectX", 3);
            intent.putExtra("aspectY", 2);
        } else {
            intent.putExtra("aspectX", 1);
            intent.putExtra("aspectY", 1);
        }
        intent.putExtra(MediaStore.EXTRA_OUTPUT, cropImageUri);
        intent.putExtra("return-data", false);
        startActivityForResult(intent, SHOW_PICTURE);
    }

    public Uri createImagePathUri(Activity context) {
        String status = Environment.getExternalStorageState();
        SimpleDateFormat timeFormatter = new SimpleDateFormat(
                "yyyyMMdd_HHmmss", Locale.CHINA);
        long time = System.currentTimeMillis();
        String imageName = timeFormatter.format(new Date(time));
        ContentValues values = new ContentValues(3);
        values.put(MediaStore.MediaColumns.DISPLAY_NAME, imageName);
        values.put(MediaStore.Images.ImageColumns.DATE_TAKEN, time);
        values.put(MediaStore.MediaColumns.MIME_TYPE, "image/jpeg");
        if (status.equals(Environment.MEDIA_MOUNTED)) {// 判断是否有SD卡,优先使用SD卡存储,当没有SD卡时使用手机存储
            imageFilePath = context.getContentResolver().insert(
                    MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);


        } else {
            imageFilePath = context.getContentResolver().insert(
                    MediaStore.Images.Media.INTERNAL_CONTENT_URI, values);
//            selectedPhotos.add(Environment.getExternalStorageDirectory() + File.separator + imageFilePath.toString());
        }

        return imageFilePath;
    }

    private void showPictureByCamera() {
        imageUriFromCamera = createImagePathUri(this);
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUriFromCamera);
        startActivityForResult(intent, Make_CAMERE);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}
